package com.fubowen.reader.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView

class SimplePageAdapter<T : IPageSimple<T>>(
    val id: Int,
    val context: Context,
    val init: (View) -> Unit
) : PagingDataAdapter<T, SimplePageAdapter<T>.ViewHolder>(DiffCallback<T>()) {
    override fun onBindViewHolder(holder: SimplePageAdapter<T>.ViewHolder, position: Int) {
        getItem(position)?.onBind(holder.itemView, id)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(id, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        init {
            init(view)
        }
    }

    class DiffCallback<T : IPageSimple<T>> : DiffUtil.ItemCallback<T>() {
        override fun areContentsTheSame(o: T, n: T) = o.isSameOfContent(n)
        override fun areItemsTheSame(o: T, n: T) = o.isSame(n)

    }
}

interface IPageSimple<T> {

    fun isSame(new: T): Boolean

    fun isSameOfContent(new: T): Boolean

    fun onBind(view: View, id: Int = 0)
}